package com.boruan.shengtangfeng.api.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.*;
import com.boruan.shengtangfeng.core.dto.*;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.enums.QuestionType;
import com.boruan.shengtangfeng.core.service.*;
import com.boruan.shengtangfeng.core.tencentEntity.OpenimQuerystateReturn;
import com.boruan.shengtangfeng.core.utils.*;
import com.boruan.shengtangfeng.core.vo.*;
import io.swagger.annotations.ApiParam;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.boruan.shengtangfeng.api.jwt.UserSubject;
import com.boruan.shengtangfeng.api.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.api.service.ILoginService;
import com.boruan.shengtangfeng.core.dto.mapper.FeedbackDtoMapper;
import com.boruan.shengtangfeng.core.enums.Sex;
import com.boruan.shengtangfeng.core.utils.weixin.WeChatAuthService;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.SubjectVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: lihaicheng
 * @Description: 登录
 * @date:2020年3月10日 上午11:14:10
 */
@Slf4j
@RestController
@SuppressWarnings("all")
@RequestMapping("/api/user")
@Api(value = "", tags = { "NO:8 用户相关接口" })
public class UserApi {
	@Autowired
	private IUserService userService;
	@Autowired
	private IQuestionService questionService;
	@Autowired
	private IAttentionService attentionService;
	@Autowired
	private IConfigService configService;
	@Autowired
	private ILoginService loginService;
	@Autowired
	private INoticeService noticeService;
	@Autowired
	private IArticleService articleService;
	@Autowired
	private IVideoService videoService;
	@Autowired
	private ISubjectService subjectService;
	@Autowired
	private IModuleService moduleService;
	@Autowired
	private IAccoladeService accoladeService;
	@Autowired
    private IGradeService gradeService;

	@Value("${system.baseUrl}")
    private String baseUrl;
	@Autowired
    private JwtUtil jwtUtil;
	@Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private WeChatAuthService weChatAuthService;
    @Autowired
    private IFeedBackService feedBackService;
    @Autowired
    private IIncorrectQuestionDao incorrectQuestionDao;
    @Autowired
    private IAttentionDao attentionDao;
    @Autowired
    private IUserFriendAndBlacklistDao userFriendAndBlacklistDao;
    @Autowired
    private IUserReportDao userReportDao;
    @Autowired
    private TencentUtil tencentUtil;
    @Value("${tencent.secretid}")
    private Long SECRETID;
    @Value("${tencent.secretkey}")
    private String SECRETKEY;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private ALiYunUtils aLiYunUtils;
    @Autowired
    private IClassParameterDao classParameterDao;


//	@GetMapping("/getRank")
//	@ApiOperation(value = "NO:11-1 获取用户排行  排行类型  1 按照做题数 2 按照正确率", notes = "")
//	public GlobalReponse<RankingListVo> getRank(Integer type) {
//	    RankingListVo rankingListVo=new RankingListVo();
//	    List<User> users=userService.getRank(type, 100);
//	    UserSubject user = JwtUtil.getCurrentJwtUser();
//	    List<UserVo> vos=UserVoMapper.MAPPER.toVo(users);
//	    int i=1;
//	    for (UserVo vo : vos) {
//	        if(vo.getId().equals(user.getId())) {
//	            rankingListVo.setUser(vo);
//	            rankingListVo.setUserRank(i);
//	        }
//	        i=i+1;
//	    }
//	    rankingListVo.setUsers(vos);
//		return GlobalReponse.success(rankingListVo);
//	}
	
	@GetMapping("/getUserIndex")
	@ApiOperation(value = "NO:8-1 获取进入个人中心的数据", notes = "")
	public GlobalReponse<UserIndex> getUserIndex() {
	    UserSubject userSubject=JwtUtil.getCurrentJwtUser();
	    User user=userService.findById(userSubject.getId());
	    UserIndex userIndex=new UserIndex();
	    userIndex.setAccount(user.getAccount());
	    userIndex.setShowLocation(user.getShowLocation());
	    if (user.getParentMobile()!=null){
            userIndex.setParentMobile(user.getParentMobile());
        }
	    userIndex.setUserSig(user.getUserSig());
	    userIndex.setId(user.getId());
	    userIndex.setHeadImage(user.getHeadImage());
	    userIndex.setMobile(user.getMobile());
	    userIndex.setUserType(user.getUserType());
	    userIndex.setName(user.getName());
	    userIndex.setSex(user.getSex());
        userIndex.setInvitationCode(user.getInvitationCode());
        userIndex.setLikeNum(user.getLikeNum());
        userIndex.setIntegral(user.getIntegral());
        userIndex.setBirthDay(user.getBirthDay());
        userIndex.setProvince(user.getProvince());
        userIndex.setCity(user.getCity());
        
        Attention search =new Attention();
        search.setUserId(userSubject.getId());
        search.setIsDeleted(false);
        Long count=attentionService.templateCount(search);
        userIndex.setFollowCount(count);
        search.setUserId(null);
        search.setFocusUserId(userSubject.getId());
        count=attentionService.templateCount(search);
        userIndex.setFansCount(count);
        Article article=new Article();
        article.setIsDeleted(false);
        article.setPublishId(userSubject.getId());
        Long articleCount=articleService.templateCount(article);
        Video video=new Video();
        video.setIsDeleted(false);
        video.setPublishId(userSubject.getId());
        Long videoCount=videoService.templateCount(video);
        
        userIndex.setPublishCount((videoCount+articleCount));
//        Map<String, String> customer=new HashMap<String, String>();
//        customer.put("head", user.getHeadImage());
//        customer.put("手机", user.getMobile());
//        customer.put("名称", user.getName());
//        customer.put("会员账号", user.getLoginName());
//        String json=JSON.toJSONString(customer);
//        json=URLEncoder.encode(json);
//        Config config=configService.findConfigByKey(Consts.CONFIG_CUSTOMER_SERVICE_URL);
//        userIndex.setCustomerServiceUrl(config.getValue()+"?uniqueId="+user.getId()+"&customer="+json);
        
        if(StringUtils.isBlank(user.getPassword())||StringUtils.isBlank(user.getSalt())) {
            userIndex.setPasswordSet(false);
        }else {
            userIndex.setPasswordSet(true);
        }
//        Notice notice=new Notice();
//        notice.setUserId(userSubject.getId());
//        notice.setIsDeleted(false);
//        notice.setReaded(false);
//        long noticeCount=noticeService.getCount(notice);
//        userIndex.setNoticeCount(noticeCount);
        Config config=configService.findConfigByKey(Consts.CONFIG_APPLE_ONLINE);
		userIndex.setOnline(config.getValue());
		config=configService.findConfigByKey(Consts.CONFIG_SHARE_QRCODE);
		userIndex.setQrcode(config.getValue());
        return GlobalReponse.success(userIndex);
	}


    /**
     * 
     * @author:刘光强
     * @date:2020年3月10日 上午11:14:10
     * @param id
     * @return
     */
    @PostMapping(value = "/updateUserInfo")
    @ApiOperation(value = "NO:8-2 更新用户信息,更新邀请码，头像上传 oss的地址，所有字段不传不更新", notes = "")
    public GlobalReponse updateUserInfo(@RequestBody UpdateUserInfo updateUserInfo) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());
        if (StringUtils.isNotBlank(updateUserInfo.getNickName())) {
            user.setName(updateUserInfo.getNickName());
        } 
        if (StringUtils.isNotBlank(updateUserInfo.getHeadImage())) {
            user.setHeadImage(updateUserInfo.getHeadImage());
        } 
        if (StringUtils.isNotBlank(updateUserInfo.getBirthDay())) {
            user.setBirthDay(updateUserInfo.getBirthDay());
        } 
        if (StringUtils.isNotBlank(updateUserInfo.getCity())) {
            user.setCity(updateUserInfo.getCity());
        } 
        if (StringUtils.isNotBlank(updateUserInfo.getProvince())) {
            user.setProvince(updateUserInfo.getProvince());
        } 
        if (StringUtils.isNotBlank(updateUserInfo.getInvitationCode())) {
            user.setInvitationCode(updateUserInfo.getInvitationCode());
        }
        if(StringUtils.isNotBlank(updateUserInfo.getParentMobile())){
            user.setParentMobile(updateUserInfo.getParentMobile());
        }
        if (updateUserInfo.getSex()!=null) {
            user.setSex(EnumUtil.getEnumByValue(Sex.class, updateUserInfo.getSex()));
        }
        if(updateUserInfo.getShowLocation()!=null){
            user.setShowLocation(updateUserInfo.getShowLocation());
        }
        userService.save(user);
        return GlobalReponse.success("操作成功");
    }
    
    /**
     * @description: 国学文章展示页
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/myArticlePage")
    @ApiOperation(value = "NO:8-3 分页获取用户的文章", notes = "")
    public GlobalReponse<PageQuery<ArticleVo>> myArticlePage(@RequestBody BasePageSearch basePageSearch) {
        Article search=new Article();
        PageQuery<Article> pageQuery = new PageQuery<Article>();
        List<Article> list= null;
        if (basePageSearch.getUserId()==null){
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            search.setPublishId(userSubject.getId());
        }else {
            search.setPublishId(basePageSearch.getUserId());
        }
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        articleService.pageQuery(pageQuery, search);
        list=pageQuery.getList();
        List<ArticleVo> vos=ArticleVoMapper.MAPPER.toVo(list);
        vos.forEach(vo->{
            if(StringUtils.isNotBlank(vo.getImages())) {
                vo.setImageList(StringUtils.split(vo.getImages(),","));
            }else {
                vo.setImageList(new String[] {});
            }
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    
    /**
     * @description: 国学视频展示页
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/myVideoPage")
    @ApiOperation(value = "NO:8-4 分页获取用户的视频", notes = "")
    public GlobalReponse<PageQuery<VideoVo>> myVideoPage(@RequestBody BasePageSearch basePageSearch) {
        Video search=new Video();
        PageQuery<Video> pageQuery = new PageQuery<Video>();
        List<Video> list= new ArrayList<>();
        if (basePageSearch.getUserId()==null){
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            search.setPublishId(userSubject.getId());
        }else {
            search.setPublishId(basePageSearch.getUserId());
        }
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        pageQuery.setPageSize(basePageSearch.getPageSize());
        videoService.pageQuery(pageQuery, search);
        list=pageQuery.getList();
        List<VideoVo> vos=VideoVoMapper.MAPPER.toVo(list);
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    /**
     * @description: 删除文章
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/deleteArticle/{articleId}")
    @ApiOperation(value = "NO:8-5 删除文章", notes = "")
    public GlobalReponse deleteArticle(@PathVariable Long articleId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Article article=articleService.findId(articleId);
        if(article.getPublishId().equals(userSubject.getId())) {
            article.setIsDeleted(true);
            article.setUpdateBy(userSubject.getName());
            article.setUpdateTime(new Date());
            articleService.save(article);
            return GlobalReponse.success();
        }else {
            return GlobalReponse.fail("不能删除别人的文章");
        }
    }
    /**
     * @description: 删除视频
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/deleteVideo/{videoId}")
    @ApiOperation(value = "NO:8-6 删除视频", notes = "")
    public GlobalReponse deleteVideo(@PathVariable Long videoId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Video video=videoService.findId(videoId);
        if(video.getPublishId().equals(userSubject.getId())) {
            video.setIsDeleted(true);
            video.setUpdateBy(userSubject.getName());
            video.setUpdateTime(new Date());
            videoService.save(video);
            return GlobalReponse.success();
        }else {
            return GlobalReponse.fail("不能删除别人的视频");
        }
    }
    /**
     * @description: 删除视频
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/getFollow")
    @ApiOperation(value = "NO:8-7 获取用户关注的人", notes = "")
    public GlobalReponse<PageQuery<MyAttentionUser>> getFollow(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<MyAttentionUser> pageQuery = new PageQuery<MyAttentionUser>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        pageQuery.setPageSize(basePageSearch.getPageSize());
        attentionService.pageMyAttention(pageQuery, userSubject.getId());
        List<MyAttentionUser> list=pageQuery.getList();
        list.forEach(vo->{
            vo.setIsFollow(true);
            Attention search =new Attention();
            search.setUserId(null);
            search.setFocusUserId(vo.getId());
            Long count=attentionService.templateCount(search);
            vo.setFansCount(count);
        });
        return GlobalReponse.success(pageQuery);
    }
    /**
     * @description: 删除视频
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/getFans")
    @ApiOperation(value = "NO:8-8 获取用户的粉丝", notes = "")
    public GlobalReponse<PageQuery<MyAttentionUser>> getFans(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<MyAttentionUser> pageQuery = new PageQuery<MyAttentionUser>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        pageQuery.setPageSize(basePageSearch.getPageSize());
        attentionService.pageMyFans(pageQuery, userSubject.getId());
        List<MyAttentionUser> list=pageQuery.getList();
        list.forEach(vo->{
            Attention search =new Attention();
            search.setUserId(null);
            search.setFocusUserId(vo.getId());
            Long count=attentionService.templateCount(search);
            vo.setFansCount(count);
        });
        return GlobalReponse.success(pageQuery);
    }
    
    @GetMapping("/getIncorrectSubject")
    @ApiOperation(value = "NO:8-9 获取有错题的学科", notes = "")
    public GlobalReponse<SubjectVo> getIncorrectSubject() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<Subject> list=subjectService.getIncorrectSubject(userSubject.getId(),0);
        return GlobalReponse.success(SubjectVoMapper.MAPPER.toVo(list));
    }

    @GetMapping("/getSelfIncorrectSubject")
    @ApiOperation(value = "NO:8-9-b 获取有自主错题的学科", notes = "")
    public GlobalReponse<SubjectVo> getSelfIncorrectSubject() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<Subject> list=subjectService.getIncorrectSubject(userSubject.getId(),1);
        return GlobalReponse.success(SubjectVoMapper.MAPPER.toVo(list));
    }

    @GetMapping("/getIncorrectQuestion/{subjectId}")
    @ApiOperation(value = "NO:8-10 获取学科下的错题", notes = "")
    public GlobalReponse<QuestionVo> getIncorrectQuestion(@PathVariable Long subjectId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<Question> questions=questionService.getIncorrectQuestion(userSubject.getId(),subjectId);

        List<QuestionVo> vos=QuestionVoMapper.MAPPER.toVo(questions);
        vos.forEach(vo->{
            vo.setCollect(questionService.isFavorites(userSubject.getId(), vo.getId()));
            List<Module> modules=moduleService.findByQuestion(vo.getId());
            if(modules.isEmpty()) {
                //TODO 不知道该放什么了，放个0防止空指针
                vo.setModuleId(0L);
            }else {
                vo.setModuleId(modules.get(0).getId());
            }
        });
        return GlobalReponse.success(vos);
    }


    @GetMapping("/getFavoritesCount")
    @ApiOperation(value = "NO:8-11 获取所有收藏数量", notes = "")
    public GlobalReponse<List<FavoritesCount>> getFavoritesCount() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<FavoritesCount> favoritesCounts=new ArrayList<>();
        
        Long questionCount=questionService.getFavoritesCount(userSubject.getId());
        FavoritesCount questionFavoritesCount=new FavoritesCount();
        questionFavoritesCount.setCount(questionCount);
        questionFavoritesCount.setType("试题");
        favoritesCounts.add(questionFavoritesCount);
        
        Long articleCount=articleService.getFavoritesCount(userSubject.getId());
        FavoritesCount articleFavoritesCount=new FavoritesCount();
        articleFavoritesCount.setCount(articleCount);
        articleFavoritesCount.setType("文章");
        favoritesCounts.add(articleFavoritesCount);
        
        Long videoCount=videoService.getFavoritesCount(userSubject.getId());
        FavoritesCount videoFavoritesCount=new FavoritesCount();
        videoFavoritesCount.setCount(videoCount);
        videoFavoritesCount.setType("视频");
        favoritesCounts.add(videoFavoritesCount);
        return GlobalReponse.success(favoritesCounts);
    }
    @GetMapping("/getFavoritesSubject")
    @ApiOperation(value = "NO:8-12 获取有收藏的学科", notes = "")
    public GlobalReponse<SubjectVo> getFavoritesSubject() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<Subject> list=subjectService.getFavoritesSubject(userSubject.getId());
        return GlobalReponse.success(SubjectVoMapper.MAPPER.toVo(list));
    }
    @GetMapping("/getFavoritesQuestion/{subjectId}")
    @ApiOperation(value = "NO:8-13 获取学科下收藏的题", notes = "")
    public GlobalReponse<QuestionVo> getFavoritesQuestion(@PathVariable Long subjectId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        List<Question> questions=questionService.getFavoritesQuestion(userSubject.getId(),subjectId);
        List<QuestionVo> vos=QuestionVoMapper.MAPPER.toVo(questions);
        vos.forEach(vo->{
            vo.setCollect(questionService.isFavorites(userSubject.getId(), vo.getId()));
            List<Module> modules=moduleService.findByQuestion(vo.getId());
            if(modules.isEmpty()) {
                //TODO 不知道该放什么了，放个0防止空指针
                vo.setModuleId(0L);
            }else {
                vo.setModuleId(modules.get(0).getId());
            }
        });
        return GlobalReponse.success(vos);
    }
    @PostMapping("/pageFavoritesArticle")
    @ApiOperation(value = "NO:8-14 分页获取收藏的文章", notes = "")
    public GlobalReponse<PageQuery<ArticleVo>> pageFavoritesArticle(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<Article> pageQuery = new PageQuery<Article>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        articleService.pageFavoritesArticle(pageQuery, userSubject.getId());
        List<ArticleVo> vos=ArticleVoMapper.MAPPER.toVo(pageQuery.getList());
        vos.forEach(vo->{
            if(StringUtils.isNotBlank(vo.getImages())) {
                vo.setImageList(StringUtils.split(vo.getImages(),","));
            }else {
                vo.setImageList(new String[] {});
            }
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    @PostMapping("/pageFavoritesVideo")
    @ApiOperation(value = "NO:8-15 分页获取收藏的文章", notes = "")
    public GlobalReponse<PageQuery<VideoVo>> pageFavoritesVideo(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<Video> pageQuery = new PageQuery<Video>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        videoService.pageFavoritesVideo(pageQuery, userSubject.getId());
        List<VideoVo> vos=VideoVoMapper.MAPPER.toVo(pageQuery.getList());
        vos.forEach(vo->{
            //是否关注
              Attention attention = null;
              //是否点赞
              Accolade accolade = null;
              if(userSubject!=null) {
                  //是否关注
                  attention = attentionService.findByFocusId(userSubject.getId(),vo.getPublishId());
                  //是否点赞
                  accolade = accoladeService.getAccolade(userSubject.getId(),vo.getId(),2);
              }
              vo.setIsAttention(null == attention ? false:true);
              vo.setIsLike(null == accolade ? false:true);
              User publisher=userService.findById(vo.getPublishId());
              vo.setInvitationCode(publisher.getInvitationCode());
          });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    @PostMapping("/pageAccoladeArticle")
    @ApiOperation(value = "NO:8-14 分页获取点赞的文章", notes = "")
    public GlobalReponse<PageQuery<ArticleVo>> pageAccoladeArticle(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<Article> pageQuery = new PageQuery<Article>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        articleService.pageAccoladeArticle(pageQuery, userSubject.getId());
        List<ArticleVo> vos=ArticleVoMapper.MAPPER.toVo(pageQuery.getList());
        vos.forEach(vo->{
            if(StringUtils.isNotBlank(vo.getImages())) {
                vo.setImageList(StringUtils.split(vo.getImages(),","));
            }else {
                vo.setImageList(new String[] {});
            }
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    @PostMapping("/pageAccoladeVideo")
    @ApiOperation(value = "NO:8-15 分页获取收藏的文章", notes = "")
    public GlobalReponse<PageQuery<VideoVo>> pageAccoladeVideo(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<Video> pageQuery = new PageQuery<Video>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        videoService.pageAccoladeVideo(pageQuery, userSubject.getId());
        List<VideoVo> vos=VideoVoMapper.MAPPER.toVo(pageQuery.getList());
        vos.forEach(vo->{
            //是否关注
            Attention attention = null;
            //是否点赞
            Accolade accolade = null;
            if(userSubject!=null) {
                //是否关注
                attention = attentionService.findByFocusId(userSubject.getId(),vo.getPublishId());
                //是否点赞
                accolade = accoladeService.getAccolade(userSubject.getId(),vo.getId(),2);
            }
            vo.setIsAttention(null == attention ? false:true);
            vo.setIsLike(null == accolade ? false:true);
            User publisher=userService.findById(vo.getPublishId());
            vo.setInvitationCode(publisher.getInvitationCode());
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    @PostMapping("/pageUserComment")
    @ApiOperation(value = "NO:8-16 分页获取评论的文章或者视频，如果返回的视频或者文章为空，则是该文章被删除了", notes = "")
    public GlobalReponse<PageQuery<ArticleVideoCommentVo>> pageUserComment(@RequestBody BasePageSearch basePageSearch) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        PageQuery<ArticleVideoCommentVo> pageQuery = new PageQuery<ArticleVideoCommentVo>();
        pageQuery.setPageNumber(basePageSearch.getPageNo());
        pageQuery.setPara("userId", userSubject.getId());
        userService.pageComment(pageQuery);
        List<ArticleVideoCommentVo> vos=pageQuery.getList();
        vos.forEach(vo->{
            if (vo.getType()==0) {
                //试题
                Question question=questionService.findById(vo.getObjectId());
                if(!question.getIsDeleted()) {
                    vo.setQuestion(QuestionVoMapper.MAPPER.toVo(question));
                }
            }else if (vo.getType()==1) {
                //文章
                Article article=articleService.findId(vo.getObjectId());
                if(!article.getIsDeleted()) {
                    vo.setArticle(ArticleVoMapper.MAPPER.toVo(article));
                }
            }else if(vo.getType()==2){
                //视频
                Video video=videoService.findId(vo.getObjectId());
                if(!video.getIsDeleted()) {
                    vo.setVideo(VideoVoMapper.MAPPER.toVo(video));
                }
                
            }
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    @PostMapping("/deleteUserComment/{type}/{id}")
    @ApiOperation(value = "NO:8-17 删除用户的评论 type 0 试题 1 文章 2视频", notes = "")
    public GlobalReponse deleteUserComment(@PathVariable Integer type,@PathVariable Long id) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        return userService.deleteUserComment(userSubject.getId(),type,id);
    }
    @PostMapping("/sendCode")
    @ApiOperation(value = "NO:8-18 修改手机号时向用户绑定的手机发送验证码", notes = "")
    public GlobalReponse sendCode() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        return userService.sendCode(userSubject.getId());
    }
    @PostMapping("/checkCode/{code}")
    @ApiOperation(value = "NO:8-19 修改手机号时校验发送的验证码", notes = "")
    public GlobalReponse checkCode(@PathVariable String code) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        return userService.checkCode(userSubject.getId(),code);
    }
    @PostMapping("/bindMobile/{mobile}/{code}")
    @ApiOperation(value = "NO:8-20 修改手机号", notes = "")
    public GlobalReponse bindMobile(@PathVariable String mobile,@PathVariable String code) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        return userService.bindMobile(userSubject.getId(),mobile,code);
    }
    @PostMapping("/feedback")
    @ApiOperation(value = "NO:8-21 用户反馈", notes = "")
    public GlobalReponse feedback(@RequestBody FeedbackDto dto) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Feedback feedback=FeedbackDtoMapper.MAPPER.toEntity(dto);
        feedback.setUserId(userSubject.getId());
        feedback.setCreateBy(userSubject.getName());
        feedback.setCreateTime(new Date());
        feedback.setIsDeleted(false);
        feedBackService.saveFeedback(feedback);
        return GlobalReponse.success("反馈成功，感谢您的宝贵意见！");
    }
    
    @PostMapping("/deleteUser")
    @ApiOperation(value = "NO:8-22 注销当前用户", notes = "")
    public GlobalReponse<Boolean> deleteUser() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user=userService.findById(userSubject.getId());
        
        user.setIsDeleted(true);
        user.setUpdateBy(userSubject.getId().toString());
        user.setUpdateTime(new Date());
        userService.save(user);
        return GlobalReponse.success();
    }
    @PostMapping("/deleteFans/{fansId}")
    @ApiOperation(value = "NO:8-23 删除并拉黑粉丝", notes = "")
    public GlobalReponse<Boolean> deleteFans(@PathVariable Long fansId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        attentionService.deleteFans(userSubject.getId(), fansId);
        return GlobalReponse.success();
    }
    
    /**
     * 
     * @author:刘光强
     * @date:2020年3月10日 上午11:14:10
     * @param id
     * @return
     */
    @PostMapping(value = "/deleteInvitationCode")
    @ApiOperation(value = "NO:8-24 删除邀请码", notes = "")
    public GlobalReponse deleteInvitationCode() {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User user = userService.findById(userSubject.getId());
        user.setInvitationCode(null);
        userService.save(user);
        return GlobalReponse.success("操作成功");
    }
    @PostMapping("/blackUser/{userId}")
    @ApiOperation(value = "NO:8-25 拉黑用户，不看这个用户的内容", notes = "")
    public GlobalReponse<Boolean> blackUser(@PathVariable Long userId) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        userService.blackUser(userSubject.getId(), userId);
        return GlobalReponse.success();
    }

    @GetMapping("/saveOrCaleStick")
    @ApiOperation(value = "NO:8-26 置顶或者取消置顶", notes = "")
    public GlobalReponse saveOrCaleStick( Long fansId) {
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        attentionService.saveOrCaleStick(userId,fansId);
        return GlobalReponse.success();
    }

//    /**
//     * 
//     * @author:刘光强
//     * @date:2020年3月10日 上午11:14:10
//     * @param id
//     * @return
//     */
//    @PostMapping(value = "/checkOldMobile")
//    @ApiOperation(value = "NO:11-19 校验原手机号", notes = "")
//    public GlobalReponse checkOldMobile(String oldMobile,String authCode) {
//        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
//        if (StringUtils.isBlank(authCode)||StringUtils.isBlank(oldMobile)) {
//            return GlobalReponse.fail("参数不能为空");
//        }
//        return userService.checkOldMobile(oldMobile, authCode);
//    }
//    /**
//     * 
//     * @author:刘光强
//     * @date:2020年3月10日 上午11:14:10
//     * @param id
//     * @return
//     */
//    @PostMapping(value = "/updateUserMobile")
//    @ApiOperation(value = "NO:11-20 更换手机号", notes = "")
//    public GlobalReponse<UserVo> updateUserMobile(String mobile,String authCode) {
//        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
//        if (StringUtils.isBlank(authCode)||StringUtils.isBlank(mobile)) {
//            return GlobalReponse.fail("参数不能为空");
//        }
//        return userService.changeMobile(mobile, authCode, userSubject.getId());
//    }

    @PostMapping("/userHome")
    @ApiOperation(value = "V4F-01 查看他人主页")
    public GlobalReponse<UserHomeVo> userHome(@ApiParam(value = "用户ID") @RequestParam(value = "userId") Long userId){
        Long myId = JwtUtil.getCurrentJwtUser().getId();
        User user=userService.findById(userId);
        UserHomeVo userHome = new UserHomeVo();
        List<OpenimQuerystateReturn> returns = tencentUtil.openimQuerystate(userId);
        if (returns!=null){
            for (OpenimQuerystateReturn aReturn : returns) {
                userHome.setIsOnline(aReturn.getStatus());
            }
        }
        userHome.setAccount(user.getAccount());
        userHome.setShowLocation(user.getShowLocation());
        if (user.getParentMobile()!=null){
            userHome.setParentMobile(user.getParentMobile());
        }
        if (user.getInvitationCode()!=null){
            userHome.setInvitationCode(user.getInvitationCode());
        }
        userHome.setHeadImage(user.getHeadImage());
        userHome.setName(user.getName());
        userHome.setAccount(user.getAccount());
        userHome.setId(user.getId());
        userHome.setSex(user.getSex());
        userHome.setCity(user.getCity());
        userHome.setUserType(user.getUserType());
        userHome.setIntegral(user.getIntegral());
        Attention single = attentionDao.createLambdaQuery().andEq(Attention::getUserId, myId).andEq(Attention::getFocusUserId, userId).andEq(Attention::getIsDeleted, false).single();
        if (single!=null){
            userHome.setIsConcern(1);
        }else {
            userHome.setIsConcern(0);
        }
        UserFriendAndBlacklist friend = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, myId).andEq(UserFriendAndBlacklist::getRelevanceId, userId).andEq(UserFriendAndBlacklist::getType, 0).andEq(UserFriendAndBlacklist::getIsDeleted, false).single();
        if (friend!=null){
            userHome.setIsFriend(1);
        }else {
            userHome.setIsFriend(0);
        }
        userHome.setLikeNum(user.getLikeNum());
        //查询关注数量
        Attention search =new Attention();
        search.setUserId(userId);
        search.setIsDeleted(false);
        Long count=attentionService.templateCount(search);
        userHome.setFollowCount(count);
        //粉丝数量
        search.setUserId(null);
        search.setFocusUserId(userId);
        count=attentionService.templateCount(search);
        userHome.setFansCount(count);
        //文章数量
        Article article=new Article();
        article.setIsDeleted(false);
        article.setPublishId(userId);
        Long articleCount=articleService.templateCount(article);
        userHome.setPublishArticle(articleCount);
        //视频数量
        Video video=new Video();
        video.setIsDeleted(false);
        video.setPublishId(userId);
        Long videoCount=videoService.templateCount(video);
        userHome.setPublishVideo(videoCount);
        return GlobalReponse.success(userHome);
    }

    @GetMapping("/getReportReason")
    @ApiOperation(value = "V4F-02 获取举报原因类型")
    public GlobalReponse<List<ReportReasons>> getReportReason(){
        return userService.getReportReason();
    }


    @PostMapping("/userReport")
    @ApiOperation(value = "V4F-03 用户举报", notes = "")
    public GlobalReponse userReport(@RequestBody UserReportDto dto) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        User person = userService.findById(dto.getPersonId());
        UserReport userReport = new UserReport();
        userReport.setInformerId(userSubject.getId());
        userReport.setInformerName(userSubject.getName());
        userReport.setCreateBy(userSubject.getId().toString());
        userReport.setReasonsId(dto.getReasonId());
        userReport.setContent(dto.getContent());
        userReport.setImages(dto.getImages());
        userReport.setPersonId(person.getId());
        userReport.setPersonName(person.getName());
        userReport.setCreateTime(new Date());
        userReport.setIsDeleted(false);
        userReportDao.insertTemplate(userReport);
        return GlobalReponse.success("反馈成功");
    }

    @PostMapping("/getSelfUpQuestion")
    @ApiOperation(value = "V4D-01 收录的错题列表")
    public GlobalReponse<PageQuery<IncorrectQuestion>> getSelfUpQuestion(@RequestBody IncorrentQuestionListDto incorrentQuestionListDto){
        //查询登录用户信息
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        //实例化分页类
        PageQuery<IncorrectQuestion> pageQuery = new PageQuery<IncorrectQuestion>();
        pageQuery.setPageNumber(incorrentQuestionListDto.getPageNo());//设置分页
        pageQuery.setPageSize(incorrentQuestionListDto.getPageSize());//设置分页
        pageQuery.setPara("userId",userSubject.getId());
        pageQuery.setPara("subjectId",incorrentQuestionListDto.getSubjectId());
        pageQuery.setPara("keywords",incorrentQuestionListDto.getKeywords());
        pageQuery.setPara("status",incorrentQuestionListDto.getStatus());
        pageQuery.setPara("dateType",incorrentQuestionListDto.getDateType());
        if (incorrentQuestionListDto.getDateType()!=null && incorrentQuestionListDto.getDateType().equals(0)){
            pageQuery.setPara("startTime",incorrentQuestionListDto.getStartTime());
            pageQuery.setPara("endTime",incorrentQuestionListDto.getEndTime());

        }
        if (incorrentQuestionListDto.getDateType()!=null && incorrentQuestionListDto.getDateType().equals(3)){
            ClassParameter classParam = classParameterDao.createLambdaQuery().andEq(ClassParameter::getIsDeleted, false).single();
            //判断上下学期
            String now = new SimpleDateFormat("MM-dd").format(new Date());
            String spring = classParam.getSpringTime();
            String autumn = classParam.getAutumnTime();
            Date nowTime = null;
            Date springTime = null;
            Date autumnTime = null;
            try {
                nowTime = DateUtils.parseDate(now, "MM-dd");
                springTime = DateUtils.parseDate(spring, "MM-dd");
                autumnTime = DateUtils.parseDate(autumn, "MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar cal = Calendar.getInstance();
            int yearD = cal.get(Calendar.YEAR);

            if (nowTime.after(autumnTime) && nowTime.before(springTime)) {
                pageQuery.setPara("startTime", yearD + "-" + classParam.getAutumnTime());
                pageQuery.setPara("endTime", yearD + "-" + classParam.getSpringTime());
            } else {
                pageQuery.setPara("startTime", yearD + "-" + classParam.getSpringTime());
                pageQuery.setPara("endTime", yearD + 1 + "-" + classParam.getAutumnTime());
            }
        }
        questionService.getSelfUpQuestion(pageQuery);
        return GlobalReponse.success(pageQuery);
    }


    @PostMapping("/upWrongQuestion")
    @ApiOperation(value = "V4D-02 上传错题")
    public GlobalReponse upWrongQuestion(@ApiParam(value = "科目Id")@RequestParam(value = "subjectId") Long subjectId,@ApiParam(value = "年级Id")@RequestParam(value = "gradeId") Long gradeId,@ApiParam(value = "错题图片地址")@RequestParam(value = "img") String img){
        Boolean flag = aLiYunUtils.aliyunImageSyncCheck(img);
        if (!flag){
            return GlobalReponse.fail("图片存在违规信息，请更换图片后重新上传");
        }
        IncorrectQuestion incorrectQuestion = new IncorrectQuestion();
        //查询登录用户信息
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        incorrectQuestion.setUserId(userSubject.getId());
        incorrectQuestion.setCreateBy(userSubject.getName());
        incorrectQuestion.setCreateTime(new Date());
        incorrectQuestion.setImg(img);
        //查询科目
        Subject subject = subjectService.findById(subjectId);
        incorrectQuestion.setSubjectId(subject.getId());
        incorrectQuestion.setSubjectName(subject.getName());
        //查询年级
        Grade grade = gradeService.findById(gradeId);
        incorrectQuestion.setGradeId(grade.getId());
        incorrectQuestion.setGradeName(grade.getName());
        incorrectQuestion.setQuestionId(0L);
        incorrectQuestion.setIsDeleted(false);
        incorrectQuestion.setType(QuestionType.XIANXIATI);
        incorrectQuestion.setStatus(1);

        incorrectQuestionDao.insertTemplate(incorrectQuestion);
        return GlobalReponse.success("保存成功");
    }

    @PostMapping("/getUserSig")
    @ApiOperation(value = "获取userSig", notes = "")
    public GlobalReponse getUserSig() {
        Long userId = JwtUtil.getCurrentJwtUser().getId();
        return userService.getUserSig(userId,SECRETID, SECRETKEY);
    }

    @GetMapping("/delIncorrectQuestion")
    @ApiOperation(value = "V4D-03 删除错题")
    public GlobalReponse delIncorrectQuestion(@RequestParam(value = "incorrectId")Long incorrectId){
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        IncorrectQuestion incorrectQuestion = questionService.findInQuestion(incorrectId);
        incorrectQuestion.setIsDeleted(true);
        incorrectQuestionDao.updateById(incorrectQuestion);
        return GlobalReponse.success("删除成功");
    }

    @PostMapping("getClassInformById")
    @ApiOperation(value = "通过班级ID获取班级全部资料，分享页专用", notes = "")
    public GlobalReponse<GetClassInformVo> getClassInformById(@ApiParam(value = " 群id")@RequestParam Long classId) {
        if (classId==null){
            return GlobalReponse.fail("请传入正确的参数");
        }
        return userService.getClassInformById(classId);
    }

}
